package net.maku.events.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.maku.events.dao.UserEarningsCardDao;
import net.maku.events.dao.UserUnlockSiteDao;
import net.maku.events.entity.ActivityBriskWalkSiteEntity;
import net.maku.events.entity.UserEarningsCardEntity;
import net.maku.events.entity.UserUnlockSiteEntity;
import net.maku.events.service.ActivityBriskWalkSiteService;
import net.maku.member.dao.MemberUserDao;
import net.maku.member.entity.MemberUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author： 张慧中
 * @Date： 2025/5/7 22:48
 * @Describe：
 */
@Service
@Slf4j
public class CleanDuplicateUnlockSiteData {
    @Autowired
    UserUnlockSiteDao userUnlockSiteDao;
    @Autowired
    MemberUserDao memberUserDao;
    @Autowired
    UserEarningsCardDao userEarningsCardDao;
    @Autowired
    ActivityBriskWalkSiteService activityBriskWalkSiteService;
    //@Scheduled(cron = "0 30 23 * * ?") // 每天 23:30 执行
    //@Transactional(rollbackFor = Exception.class)
    public void cleanDuplicateUnlockSiteData() {
        log.info("开始执行清理 user_unlock_site 和 user_earnings_card 重复数据任务...");

        try {
            // 1️⃣ 清理 user_unlock_site 表
            cleanUnlockSiteDuplicates();

            // 2️⃣ 清理 user_earnings_card 表
            cleanEarningsCardDuplicates();

            log.info("数据清理任务执行完成");
        } catch (Exception e) {
            log.error("数据清理任务执行失败", e);
            throw e;
        }
    }

    /**
     * 清理 user_unlock_site 表的重复数据
     */
    private void cleanUnlockSiteDuplicates() {
        // 查询所有重复的 userId + walkActivitySiteId 组合
        List<Map<String, Object>> duplicates = userUnlockSiteDao.selectList(new QueryWrapper<UserUnlockSiteEntity>()
                        .groupBy("user_id", "walk_activity_site_id")
                        .having("COUNT(*) > 1"))
                .stream()
                .map(entity -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("user_id", entity.getUserId());
                    map.put("walk_activity_site_id", entity.getWalkActivitySiteId());
                    return map;
                })
                .collect(Collectors.toList());

        for (Map<String, Object> duplicate : duplicates) {
            Long userId = (Long) duplicate.get("user_id");
            Long siteId = (Long) duplicate.get("walk_activity_site_id");

            // 获取该组合下所有记录
            List<UserUnlockSiteEntity> records = userUnlockSiteDao.selectList(new QueryWrapper<UserUnlockSiteEntity>()
                    .eq("user_id", userId)
                    .eq("walk_activity_site_id", siteId)
                    .orderByDesc("id")); // 按 id 倒序排列

            if (records.size() > 1) {
                // 保留第一条，其余删除
                List<Long> idsToDelete = records.stream()
                        .skip(1)
                        .map(UserUnlockSiteEntity::getId)
                        .collect(Collectors.toList());

                // 删除重复记录
                userUnlockSiteDao.deleteBatchIds(idsToDelete);

                // 获取站点信息（用于计算积分）
                ActivityBriskWalkSiteEntity siteEntity = activityBriskWalkSiteService.getById(siteId);
                if (siteEntity != null) {
                    double unlockPoints = siteEntity.getUnlockPoints(); // 确保字段名正确

                    // 扣除重复解锁所获得的积分
                    double totalPointsToDeduct = unlockPoints * (records.size() - 1);

                    // 更新用户积分（假设 member_user 表有 points 字段）
                    if (totalPointsToDeduct > 0) {
                        MemberUserEntity user = memberUserDao.selectById(userId);
                        if (user != null) {
                            user.setPoints(user.getPoints() - totalPointsToDeduct);
                            memberUserDao.updateById(user);
                        }
                    }

                    log.info("已清理 user_unlock_site 重复数据：userId={}, siteId={}，共删除 {} 条记录，扣除积分 {:.2f}",
                            userId, siteId, idsToDelete.size(), totalPointsToDeduct);
                }
            }
        }
    }

    /**
     * 清理 user_earnings_card 表的重复数据
     */
    private void cleanEarningsCardDuplicates() {
        // 查询所有重复的 userId + briskWalkSiteId 组合
        List<Map<String, Object>> duplicates = userEarningsCardDao.selectList(new QueryWrapper<UserEarningsCardEntity>()
                        .groupBy("user_id", "brisk_walk_site_id")
                        .having("COUNT(*) > 1"))
                .stream()
                .map(entity -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("user_id", entity.getUserId());
                    map.put("brisk_walk_site_id", entity.getBriskWalkSiteId());
                    return map;
                })
                .collect(Collectors.toList());

        for (Map<String, Object> duplicate : duplicates) {
            Long userId = (Long) duplicate.get("user_id");
            Long siteId = (Long) duplicate.get("brisk_walk_site_id");

            // 获取该组合下所有记录
            List<UserEarningsCardEntity> records = userEarningsCardDao.selectList(new QueryWrapper<UserEarningsCardEntity>()
                    .eq("user_id", userId)
                    .eq("brisk_walk_site_id", siteId)
                    .orderByDesc("id")); // 按 id 倒序

            if (records.size() > 1) {
                // 删除除第一条外的所有记录
                List<Long> idsToDelete = records.stream()
                        .skip(1)
                        .map(UserEarningsCardEntity::getId)
                        .collect(Collectors.toList());

                userEarningsCardDao.deleteBatchIds(idsToDelete);

                log.info("已清理 user_earnings_card 重复数据：userId={}, siteId={}，共删除 {} 条记录",
                        userId, siteId, idsToDelete.size());
            }
        }
    }

}
